<?php

namespace app\admin\model;

use think\Model;

class RoleModel extends Model
{
    protected $table = 'roles';

    protected $hidden = [];

    protected $autoWriteTimestamp = true;

    /**
     * 获取角色下的权限
     */
    public function permissions()
    {
        return $this->hasMany(PermissionModel::class, 'role_id', 'id');
    }

    public static function lists($request)
    {
        $lists = RoleModel::order('id asc');
        if (!isset($request['page']) || empty($request['page'])) {
            $request['page'] = "1";
        }
        if (!isset($request['limit']) || empty($request['limit'])) {
            $request['limit'] = "10";
        }
        if (isset($request['name']) && $request['name'] != '') {
            $lists = $lists->where("name", "like", "%" . $request['name'] . "%");
        }
        if (isset($request['status']) && $request['status'] != '') {
            $lists = $lists->where("status", $request['status']);
        }
        $data['count'] = $lists->count();
        $data['lists'] = $lists->limit(($request['page'] - 1) * $request['limit'], $request['limit'])->select();
        return baseResponse(0, '获取角色列表成功', $data);
    }

    public static function createSubmit($request)
    {
        $role = RoleModel::where('name', $request['name'])->find();
        if ($role) {
            return baseResponse(1, '角色已存在');
        } else {
            $role = RoleModel::create([
                'name' => $request['name'],
                'describe' => $request['describe'],
                'status' => $request['status'],
            ]);
            PermissionModel::updatePermission($role['id'], $request['menus']);
            return baseResponse(0, '角色创建成功');
        }
    }

    public static function updateSubmit($request, $id)
    {
        $role = RoleModel::where('name', $request['name'])->where('id', '<>', $id)->find();
        if ($role) {
            return baseResponse(1, '角色已存在或者权限为空');
        } else {
            $role = RoleModel::update([
                'id' => $id,
                'name' => $request['name'],
                'describe' => $request['describe'],
                'status' => $request['status'],
            ]);
            PermissionModel::updatePermission($id, $request['menus']);
            return baseResponse(0, '角色编辑成功');
        }
    }
}
